<!DOCTYPE html>
<html lang="en">
 <head> 
  <meta charset="UTF-8" /> 
  <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
  <title>玩家客户端</title> 
  <script crossorigin="anonymous" integrity="sha512-WL6WGKMPBiM9PnHRYIn5YEtq0Z8XP4fkVb4qy7PP4vhmYQErJ/dySyXuFIMDf1eEYCXCrQrMJfkNwKc9gsjTjA==" src="https://lib.baomitu.com/socket.io/4.2.0/socket.io.js"></script>

 </head> 
 <body> 
  <div id="title">玩家客户端</div>
  <div>[状态日志]：</div>
  <div class="log" id="logoutput"></div>
  <div>[消息广播]：</div>
  <div class="message" id="messageoutput"></div>
  <div>[消息发送]：</div>
  <textarea id="messagetext"></textarea>
  <button onclick="send()">发送</button> 
  <div>[房间列表]：</div>
  <div class="roomList" id="roomList"></div>


  <script>

let servers = [
    "iphone-stun.strato-iphone.de:3478",
    "numb.viagenie.ca:3478",
    "stun.12connect.com:3478",
    "stun.12voip.com:3478",
    "stun.1und1.de:3478",
    "stun.3cx.com:3478",
    "stun.acrobits.cz:3478",
    "stun.actionvoip.com:3478",
    "stun.advfn.com:3478",
    "stun.altar.com.pl:3478",
    "stun.antisip.com:3478",
    "stun.avigora.fr:3478",
    "stun.bluesip.net:3478",
    "stun.cablenet-as.net:3478",
    "stun.callromania.ro:3478",
    "stun.callwithus.com:3478",
    "stun.cheapvoip.com:3478",
    "stun.cloopen.com:3478",
    "stun.commpeak.com:3478",
    "stun.cope.es:3478",
    "stun.counterpath.com:3478",
    "stun.counterpath.net:3478",
    "stun.dcalling.de:3478",
    "stun.demos.ru:3478",
    "stun.dus.net:3478",
    "stun.easycall.pl:3478",
    "stun.easyvoip.com:3478",
    "stun.ekiga.net:3478",
    "stun.epygi.com:3478",
    "stun.etoilediese.fr:3478",
    "stun.faktortel.com.au:3478",
    "stun.freecall.com:3478",
    "stun.freeswitch.org:3478",
    "stun.freevoipdeal.com:3478",
    "stun.gmx.de:3478",
    "stun.gmx.net:3478",
    "stun.halonet.pl:3478",
    "stun.hoiio.com:3478",
    "stun.hosteurope.de:3478",
    "stun.infra.net:3478",
    "stun.internetcalls.com:3478",
    "stun.intervoip.com:3478",
    "stun.ipfire.org:3478",
    "stun.ippi.fr:3478",
    "stun.ipshka.com:3478",
    "stun.it1.hr:3478",
    "stun.ivao.aero:3478",
    "stun.jumblo.com:3478",
    "stun.justvoip.com:3478",
    "stun.l.google.com:19302",
    "stun.linphone.org:3478",
    "stun.liveo.fr:3478",
    "stun.lowratevoip.com:3478",
    "stun.lundimatin.fr:3478",
    "stun.mit.de:3478",
    "stun.miwifi.com:3478",
    "stun.modulus.gr:3478",
    "stun.myvoiptraffic.com:3478",
    "stun.netappel.com:3478",
    "stun.netgsm.com.tr:3478",
    "stun.nfon.net:3478",
    "stun.nonoh.net:3478",
    "stun.nottingham.ac.uk:3478",
    "stun.ooma.com:3478",
    "stun.ozekiphone.com:3478",
    "stun.pjsip.org:3478",
    "stun.poivy.com:3478",
    "stun.powervoip.com:3478",
    "stun.ppdi.com:3478",
    "stun.qq.com:3478",
    "stun.rackco.com:3478",
    "stun.rockenstein.de:3478",
    "stun.rolmail.net:3478",
    "stun.rynga.com:3478",
    "stun.schlund.de:3478",
    "stun.sigmavoip.com:3478",
    "stun.sip.us:3478",
    "stun.sipdiscount.com:3478",
    "stun.sipgate.net:10000",
    "stun.sipgate.net:3478",
    "stun.siplogin.de:3478",
    "stun.sipnet.net:3478",
    "stun.sipnet.ru:3478",
    "stun.sippeer.dk:3478",
    "stun.siptraffic.com:3478",
    "stun.sma.de:3478",
    "stun.smartvoip.com:3478",
    "stun.smsdiscount.com:3478",
    "stun.solcon.nl:3478",
    "stun.solnet.ch:3478",
    "stun.sonetel.com:3478",
    "stun.sonetel.net:3478",
    "stun.sovtest.ru:3478",
    "stun.srce.hr:3478",
    "stun.stunprotocol.org:3478",
    "stun.t-online.de:3478",
    "stun.tel.lu:3478",
    "stun.telbo.com:3478",
    "stun.tng.de:3478",
    "stun.twt.it:3478",
    "stun.uls.co.za:3478",
    "stun.unseen.is:3478",
    "stun.usfamily.net:3478",
    "stun.viva.gr:3478",
    "stun.vivox.com:3478",
    "stun.vo.lu:3478",
    "stun.voicetrading.com:3478",
    "stun.voip.aebc.com:3478",
    "stun.voip.blackberry.com:3478",
    "stun.voip.eutelia.it:3478",
    "stun.voipblast.com:3478",
    "stun.voipbuster.com:3478",
    "stun.voipbusterpro.com:3478",
    "stun.voipcheap.co.uk:3478",
    "stun.voipcheap.com:3478",
    "stun.voipgain.com:3478",
    "stun.voipgate.com:3478",
    "stun.voipinfocenter.com:3478",
    "stun.voipplanet.nl:3478",
    "stun.voippro.com:3478",
    "stun.voipraider.com:3478",
    "stun.voipstunt.com:3478",
    "stun.voipwise.com:3478",
    "stun.voipzoom.com:3478",
    "stun.voys.nl:3478",
    "stun.voztele.com:3478",
    "stun.webcalldirect.com:3478",
    "stun.wifirst.net:3478",
    "stun.xtratelecom.es:3478",
    "stun.zadarma.com:3478",
    "stun1.faktortel.com.au:3478",
    "stun1.l.google.com:19302",
    "stun2.l.google.com:19302",
    "stun3.l.google.com:19302",
    "stun4.l.google.com:19302",
    "stun.nextcloud.com:443",
    "relay.webwormhole.io:3478"
];

let socket = io("ws://115.28.163.25:3004");
let uid=getQueryVariable("uid")
document.getElementById("title").innerHTML=`玩家客户端[UID:${uid}]`
document.title=`玩家客户端[UID:${uid}]`
let roomId;
function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

let pc = null;
let dc = null;

//createRtc()

let configuration= {"iceServers":[{"urls":["stun:stun.epygi.com:3478"]}],"iceTransportPolicy":"all","iceCandidatePoolSize":"0"}

// for (let item of servers){
//     configuration.iceServers.push(
//         { urls: `stun:${item}` }
//     )
// }
configuration.iceServers

function createRtc(){

    if(pc){
        pc.close()
    }
    if(dc){
        dc.close()
    }

    pc = new RTCPeerConnection(configuration);

    // 同样的监听SDP变化的事件，在SPD创建完成的时候打印他
    pc.onicegatheringstatechange = () => {
        if (pc.iceGatheringState === "complete") {
            console.log(JSON.stringify(pc.localDescription));
            console.log(123)
            socket.emit("setAnswer", {roomId,uid,answer:JSON.stringify(pc.localDescription)});
            //socket.disconnect(true,uid)
            //document.getElementById("logoutput").innerHTML=JSON.stringify(pc.localDescription)
        }
    }

    pc.onconnectionstatechange = (e) => {
        switch(pc.connectionState) {
            case "connected":
            // The connection has become fully connected
            console.log(`connected`)
            break;
            case "disconnected":
            console.log(`disconnected`)
            case "failed":
            console.log(`failed`)
            break;
            case "closed":
            // The connection has been closed
            console.log(`closed`)
            break;
        }
    }

    // 监听数据通道的事件，并添加上事件，保存一下这条数据通道
    pc.ondatachannel = (e) => {
        console.log("data channel");
        dc = e.channel;
        dc.onmessage = (e) => {
            console.log("get message", e.data);
            updateMessageBox(`${e.data}`)
        }
        dc.onopen = async (e) => console.log("channel opened");
    }
}

socket.on("roomUpdate", (data) => {
   // console.log(data)
    let roomListDom =`<div>`
     for(let item of data){
        roomListDom+=`<div>${item.roomId} <button onclick="joinRoom('${item.roomId}')">加入</button></div>`
     }
     roomListDom+=`</div>`
    document.getElementById("roomList").innerHTML=roomListDom
});

function joinRoom(_roomId){
    console.log("加入房间")
    roomId=_roomId
    socket.emit("join", {uid,roomId});
}

socket.on("connect", () => {
    // or with emit() and custom event names
    //socket.emit("join", {uid,roomId});
});

socket.on("disconnected", () => {
    // or with emit() and custom event names
    //socket.emit("join", {uid,roomId});
});

socket.on("setOffer"+uid, data => {
    console.log("setOffer",data)
    createRtc()
    setOffer(data.offer)
});


async function setOffer(offer) {
	await pc.setRemoteDescription(JSON.parse(offer));
	console.log("Offer Set",);
    createAnswer()
}


function updateMessageBox(data) {
    let node =document.createElement("div");
    node.innerHTML=data
    document.getElementById("messageoutput").appendChild(node)
}

async function createAnswer() {
	const answer = await pc.createAnswer();
    console.log(answer)
	await pc.setLocalDescription(answer);
}

async function send() {
    let message=document.getElementById("messagetext").value;
    if(pc.connectionState=="connected"){
        dc.send(message);
    }
}

</script>  
 </body>
</html>